# [级别] 时间戳 - 消息内容
log_entries = [
    "[ERROR] 2024-09-29 17:12:22 - Database connection failed",
    "[INFO]  2024-09-29 17:12:25 - User login successful",
    "[WARN]  2024-09-29 17:12:30 - High memory usage detected"
]
def parse_log_entry_simple(entry):
    # 查找日志级别结束位置
    level_end = entry.find(']')
    level = entry[1:level_end].strip()
    
    # 查找时间戳结束位置
    time_start = level_end + 1
    time_end = entry.find(' - ')
    timestamp = entry[time_start:time_end].strip()
    
    # 提取消息内容
    message = entry[time_end + 3:].strip()
    
    # 返回三个独立的变量
    return level, timestamp, message

# 解析并显示所有日志
print("日志解析结果:")
for entry in log_entries:
    level, timestamp, message = parse_log_entry_simple(entry)
    print(f"日志: {entry}")
    print(f"提取结果: 级别={level}, 时间={timestamp}, 消息={message}")
# Output:日志解析结果:
# 日志: [ERROR] 2024-09-29 17:12:22 - Database connection failed
# 提取结果: 级别=ERROR, 时间=2024-09-29 17:12:22, 消息=Database connection failed
# 日志: [INFO]  2024-09-29 17:12:25 - User login successful
# 提取结果: 级别=INFO, 时间=2024-09-29 17:12:25, 消息=User login successful
# 日志: [WARN]  2024-09-29 17:12:30 - High memory usage detected
# 提取结果: 级别=WARN, 时间=2024-09-29 17:12:30, 消息=High memory usage detected    
    
    
def parse_log_entry_dict(entry):
    level_end = entry.find(']')
    level = entry[1:level_end].strip()
    
    time_start = level_end + 2
    time_end = entry.find(' - ')
    timestamp = entry[time_start:time_end].strip()
    
    message = entry[time_end + 3:].strip()
    
    return {
        'level': level,
        'timestamp': timestamp,
        'message': message
    }

print("\n使用字典版本:")
for entry in log_entries:
    parsed = parse_log_entry_dict(entry)
    print(f"级别: {parsed['level']}")
    print(f"时间: {parsed['timestamp']}")
    print(f"消息: {parsed['message']}")
    print("-" * 30)
    # Output:使用字典版本:
    # 级别: ERROR
    # 时间: 2024-09-29 17:12:22
    # 消息: Database connection failed
    # ------------------------------
    # 级别: INFO
    # 时间: 2024-09-29 17:12:25
    # 消息: User login successful
    # ------------------------------
    # 级别: WARN
    # 时间: 2024-09-29 17:12:30
    # 消息: High memory usage detected
    # ------------------------------